import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddBillRule from './components/AddBillRule';
import UpdateBillRule from './components/UpdateBillRule';
import type { ChargeSchemeDetail, ChargeSchemeTableItem } from './data';
import { getSchemeDetails, pageQuerySchemeList, removeFeeRule } from './service';

const TableList: React.FC = () => {
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [billRuleModal, setBillRuleModal] = useState<boolean>(false);
  const [updateModal, setUpdateModal] = useState<boolean>(false);
  const [currItem, setCurrItem] = useState<ChargeSchemeDetail | null>(null);
  const columns: ProColumns<ChargeSchemeTableItem>[] = [
    {
      title: '规则编号',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '规则名称',
      dataIndex: 'name',
    },
    {
      title: '规则描述',
      dataIndex: 'comment',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      hideInSearch: true,
      render: (_, record) => {
        if (record.update_time) {
          return record.update_time;
        } else {
          return '未知';
        }
      },
    },
    {
      title: '操作',
      // @ts-ignore
      valueType: 'option',
      hideInSearch: true,
      render: (_, record, x, action) => [
        <>
          <a
            onClick={async () => {
              const curr = await getSchemeDetails(record.id);
              setCurrItem(curr);
              setUpdateModal(true);
            }}
          >
            修改
          </a>
          <a
            onClick={() => {
              Modal.confirm({
                title: `删除规则`,
                content: (
                  <>
                    <Divider />
                    <p>
                      确认要删除
                      <span style={{ padding: '0 5px', fontWeight: 'bolder' }}>{record.name}</span>?
                    </p>
                  </>
                ),
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const hide = message.loading('正在删除');
                  try {
                    const res = await removeFeeRule({ id: record.id });
                    hide();
                    if (res.code === SUCCESS_CODE) {
                      message.success('删除成功');
                      action?.reload();
                      return true;
                    }
                    message.error(`${res.message}`);
                    return false;
                  } catch (error) {
                    message.error('当前收费规则已配置,无法删除');
                    return false;
                  }
                },
                centered: true,
                width: '35vw',
                style: { height: '20vw' },
              });
            }}
          >
            删除
          </a>
        </>,
      ],
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<ChargeSchemeTableItem>
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
        }}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        headerTitle="计费规则列表"
        actionRef={actionRef}
        scroll={{ x: true }}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<ChargeSchemeTableItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        tableAlertRender={() => false}
        params={{
          sorter,
        }}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return pageQuerySchemeList({ page, pageSize, ...filter });
        }}
        toolBarRender={() => [
          <>
            <Button
              type="primary"
              onClick={() => {
                setBillRuleModal(true);
              }}
            >
              <PlusOutlined />
              添加
            </Button>
          </>,
        ]}
        columns={columns}
        rowSelection={false}
      />
      {billRuleModal && (
        <AddBillRule
          visible={billRuleModal}
          setUnvisible={() => setBillRuleModal(false)}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
      {currItem && updateModal && (
        <UpdateBillRule
          visible={updateModal}
          ruleData={currItem}
          setUnvisible={() => setUpdateModal(false)}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
